package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.help.condition.ConditionHelper;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.parent.service.ListGroupService;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.KeyValuePojo;
import com.xbongbong.paas.pojo.SyncConditionPojo;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.PublicPoolErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.publicgroup.pojo.PublicGroupFormTreePojo;
import com.xbongbong.pro.publicgroup.pojo.PublicGroupItemListPojo;
import com.xbongbong.pro.publicgroup.pojo.PublicGroupListPojo;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupGetConditionDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSetDeleteDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSetItemDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSetListDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSetSaveDTO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupGetConditionVO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupItemListVO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSetDeleteVO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSetItemVO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSetListVO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSetSaveVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.PublicGroupEntity;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.enums.CustomerExpressEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.help.MarketManagementBusinessHelp;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.PublicGroupModel;
import com.xbongbong.saas.model.PublicGroupSeniorModel;
import com.xbongbong.saas.service.PublicGroupService;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @description: 公海池分组
 * @Author: hongxiao
 * @date: 2019-03-03 16:50
 * @since v1.0
 */
@Service("publicGroupService")
public class PublicGroupServiceImpl implements PublicGroupService {
    private static final Logger LOG = LoggerFactory.getLogger(PublicGroupServiceImpl.class);
    /**
     * 每个模板最多10个分组
     */
    private static final int MAX_GROUP_COUNT = 10;

    @Resource
    private PublicGroupModel publicGroupModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserModel userModel;
    @Resource
    private UserService userService;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private ListGroupService listGroupService;
    @Resource
    private MarketManagementBusinessHelp marketManagementBusinessHelp;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PublicGroupSeniorModel publicGroupSeniorModel;

    @Resource
    private ConditionHelper conditionHelper;

    @Override
    public PublicGroupSetListVO setList(PublicGroupSetListDTO setListDTO) throws XbbException {
        PublicGroupSetListVO setListVO = new PublicGroupSetListVO();

        String corpid = setListDTO.getCorpid();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("corpid", corpid);
        param.put("orderByStr", "sort desc");
        List<PublicGroupEntity> publicGroupList = publicGroupModel.findEntitys(param);
        List<PublicGroupListPojo> list = new ArrayList<>();
        for (PublicGroupEntity entity : publicGroupList) {
            PublicGroupListPojo listPojo = new PublicGroupListPojo();
            BeanUtil.copyProperties(entity, listPojo);
            listPojo.setIsEnable(entity.getEnable());
            list.add(listPojo);
        }

        // 获取已启用的模板
        List<PaasFormEntityExt> templateList = paasFormModel.getEnableFormListDistributor(corpid, setListDTO.getBusinessType(), 0);
        // 客户应用id
        Long appId = null;
        List<PublicGroupFormTreePojo> templateTree = new ArrayList<>();
        for (PaasFormEntityExt entityExt : templateList) {
            //过滤掉没有使用权限的SASS多模板表单
            List<OptionalRangeEntity> optionalRangeList = JSONObject.parseArray(entityExt.getPermission(), OptionalRangeEntity.class);
            Boolean noPermission = optionalRangeList != null && !optionalRangeList.isEmpty() && paasFormHelp.haveNoPermission(setListDTO.getLoginUser(), optionalRangeList);
            if (Objects.equals(entityExt.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && RedundantTemplateTypeEnum.isMultiTemplate(entityExt.getBusinessType()) && noPermission) {
                continue;
            }
            //
            if (Objects.isNull(appId)) {
                appId = entityExt.getAppId();
            }
            long id = entityExt.getId();
            PublicGroupFormTreePojo pojo = new PublicGroupFormTreePojo();
            pojo.setFormId(id);
            pojo.setName(entityExt.getName());
            pojo.setNode(getSubPublicGroup(id, list));
            templateTree.add(pojo);
        }

        setListVO.setFormTree(templateTree);
        setListVO.setAppId(appId);
        setListVO.setSaasMark(SaasMarkEnum.SAAS.getCode());

        return setListVO;
    }

    @Override
    public PublicGroupItemListVO groupItemList(PublicGroupSetListDTO setListDTO) throws XbbException {
        PublicGroupItemListVO setListVO = new PublicGroupItemListVO();
        List<PublicGroupItemListPojo> groupSetItem = new ArrayList<>();
        PaasAppEntity marketManagementApp = paasAppModel.getByAlias(XbbRefTypeEnum.MARKET_MANAGEMENT.getAlias(), setListDTO.getCorpid());
        Boolean standardWithFeeType = packageHelp.isStandardWithFeeType(setListDTO.getCorpid());
        if (Objects.nonNull(marketManagementApp) && Objects.equals(marketManagementApp.getEnable(), BasicConstant.ONE) && !standardWithFeeType) {
            // 线索应用关闭是没有这个线索公海池设置
            PublicGroupItemListPojo cluePojo = new PublicGroupItemListPojo();
            cluePojo.setAlias("trailSetGroup");
            cluePojo.setBusinessType(XbbRefTypeEnum.CLUE.getCode());
            cluePojo.setName(I18nMessageUtil.getMessage(StringConstant.CLUE_PUBLIC_SET));
            groupSetItem.add(cluePojo);
        }
        PublicGroupItemListPojo customerPojo = new PublicGroupItemListPojo();
        customerPojo.setAlias("customerSetGroup");
        customerPojo.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        customerPojo.setName(I18nMessageUtil.getMessage(StringConstant.CUSTOMER_PUBLIC_SET));
        groupSetItem.add(customerPojo);
        setListVO.setGroupSetItem(groupSetItem);
        return setListVO;
    }

    @Override
    public PublicGroupSetItemVO setItem(PublicGroupSetItemDTO setItemDTO) throws XbbException {
        PublicGroupSetItemVO setItemVO = new PublicGroupSetItemVO();

        String corpid = setItemDTO.getCorpid();
        Long id = setItemDTO.getId();

        PublicGroupEntity publicGroup = publicGroupModel.getByKey(id, corpid);
        if (publicGroup == null) {
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218007);
        }


        JSONArray jsonData = publicGroup.getJsonData();
        JSONArray scopeRule = publicGroup.getScopeRule();

        if (jsonData == null) {
            jsonData = new JSONArray();
        }
        // 处理有员工或部门的筛选条件
        conditionHelper.handleUserConditions(corpid,jsonData);

        List<OptionalRangeEntity> scopeRuleData;
        try {
            scopeRuleData = scopeRule.toJavaList(OptionalRangeEntity.class);
        } catch (JSONException e) {
            scopeRuleData = new ArrayList<>();
        }


        Long formId = publicGroup.getFormId();
        String formName = "";
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        if (paasFormEntityExt != null) {
            formName = paasFormEntityExt.getName();
        }

        BeanUtil.copyProperties(publicGroup, setItemVO);

        setItemVO.setFormName(formName);
        setItemVO.setJsonData(jsonData);
        setItemVO.setScopeRule(scopeRuleData);
        return setItemVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PublicGroupSetSaveVO setSave(PublicGroupSetSaveDTO setSaveDTO) throws XbbException {
        PublicGroupSetSaveVO setSaveVO = new PublicGroupSetSaveVO();

        String corpid = setSaveDTO.getCorpid();
        String userId = setSaveDTO.getUserId();

        // 参数
        Long id = setSaveDTO.getId();
        String name = setSaveDTO.getName();
        Long formId = setSaveDTO.getFormId();
        List<OptionalRangeEntity> scopeRule = setSaveDTO.getScopeRule();
        JSONArray jsonData = setSaveDTO.getJsonData();

        // 设置默认值
        id = id != null ? id : 0L;
        scopeRule = scopeRule != null ? scopeRule : new ArrayList<>();
        jsonData = jsonData != null ? jsonData : new JSONArray();


        boolean isNew = id <= 0L;
        PublicGroupEntity publicGroup = new PublicGroupEntity();
        if (!isNew) {
            publicGroup = publicGroupModel.getByKey(id, corpid);
            if (publicGroup == null) {
                throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218007);
            }
            // 克隆旧对象用来生成更新日志;
        }

        PaasFormEntityExt formEntityExt = paasFormModel.getByKey(formId, corpid);
        if (formEntityExt == null) {
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218008);
        }

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("corpid", corpid);
        // 每个模板最多10个分组
        param.put("formId", formId);
        if (isNew) {
            //新建
            int allCount = publicGroupModel.getEntitysCount(param);
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias("publicGroupNum", corpid);
            int maxNum = Objects.nonNull(companyConfigEntity) ? StringUtil.toInt(companyConfigEntity.getConfigValue(), MAX_GROUP_COUNT) : MAX_GROUP_COUNT;
            if (allCount >= maxNum) {
                throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218010, PublicPoolErrorCodeEnum.API_ERROR_218010.getMsg(), maxNum);
            }
            publicGroup.setCorpid(corpid);
            publicGroup.setCreatorId(userId);
            publicGroup.setScopeEnable(BasicConstant.IS_USE);
        }

        param.put("idNotEqual", id);
        param.put("name", name);
        Integer nameCount = publicGroupModel.getEntitysCount(param);
        if (nameCount > 0) {
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218009);
        }

        JSONArray scopeRuleArray = new JSONArray();
        scopeRuleArray.addAll(scopeRule);
        JSONArray jsonDataArray = new JSONArray();
        jsonDataArray.addAll(jsonData);


        publicGroup.setName(name);
        publicGroup.setFormId(formId);
        publicGroup.setEnable(setSaveDTO.getEnable());
        publicGroup.setJsonData(jsonDataArray);
        publicGroup.setScopeRule(scopeRuleArray);
        publicGroup.setModifierId(userId);
        publicGroup.setUpdateTime((long) DateUtil.getInt());

        try {
            publicGroupModel.save(publicGroup);
        } catch (Exception e) {
            LOG.error("保存公海池分组出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 日志
        String loginUserName = setSaveDTO.getLoginUserName();
        String operate = isNew ? I18nMessageUtil.getMessage(I18nStringConstant.ADD_PUBLIC_GROUP) : I18nMessageUtil.getMessage(I18nStringConstant.UPDATE_PUBLIC_GROUP) ;
        OperateTypeEnum operateType = isNew ? OperateTypeEnum.NEW : OperateTypeEnum.EDIT;
        String memo = loginUserName + operate + name;
        mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.PUBLIC_GROUP, operateType, publicGroup.getId().toString(), I18nMessageUtil.getMessage(StringConstant.PUBLIC_GROUP_RULE_SET), memo, setSaveDTO.getHttpHeader());

        return setSaveVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PublicGroupSetDeleteVO setDelete(PublicGroupSetDeleteDTO setDeleteDTO) throws XbbException {
        PublicGroupSetDeleteVO setDeleteVO = new PublicGroupSetDeleteVO();

        // TODO 公海池分组设置权限
        PublicGroupEntity publicGroup = publicGroupModel.getByKey(setDeleteDTO.getId(), setDeleteDTO.getCorpid());
        if (publicGroup == null) {
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218007);
        }

        publicGroup.setDel(DelEnum.DELETE.getDel());
        publicGroup.setModifierId(setDeleteDTO.getUserId());
        publicGroup.setUpdateTime((long) DateUtil.getInt());

        try {
            publicGroupModel.save(publicGroup);
        } catch (Exception e) {
            LOG.error("删除公海池分组出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 日志
        String loginUserName = setDeleteDTO.getLoginUserName();
        String memo = loginUserName + "删除了公海分组:" + publicGroup.getName();
        mongoLogHelp.buildLog(setDeleteDTO.getCorpid(), setDeleteDTO.getUserId(), loginUserName, OperateModuleTypeEnum.PUBLIC_GROUP, OperateTypeEnum.DELETE, publicGroup.getId().toString(), I18nMessageUtil.getMessage(StringConstant.PUBLIC_GROUP_RULE_SET), memo, setDeleteDTO.getHttpHeader());

        return setDeleteVO;
    }

    @Override
    public PublicGroupGetConditionVO getCondition(PublicGroupGetConditionDTO getConditionDTO) throws XbbException {
        PublicGroupGetConditionVO getConditionVO = new PublicGroupGetConditionVO();
        String corpid = getConditionDTO.getCorpid();
        Long formId = getConditionDTO.getFormId();
        Integer businessType = getConditionDTO.getBusinessType();

        PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (explainEntity == null) {
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218011);
        }
        //标准模式客户公海池
        boolean customerStandardMode = Objects.equals(businessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && !commonHelp.isCustomerPublicPoolSeniorModel(corpid);
        //标准模式线索公海池
        boolean clueStandardMode = Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode()) && !commonHelp.isCluePublicPoolSeniorModel(corpid);
        String explains = explainEntity.getExplains();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(explainEntity.getBusinessType());

        List<String> removeAttrs = new ArrayList<>();
        if (Objects.equals(getConditionDTO.getAutoAllocation(), 1)) {
            // 线索自动分配那里，需要去掉以下这几个字段
            removeAttrs = Arrays.asList(ClueEnum.LAST_CONNECT_TIME.getAttr(), ClueEnum.BACK_PUBLIC_DATE.getAttr(),
                    ClueEnum.DISTRIBUTION_DATE.getAttr(), ClueEnum.UPDATE_TIME.getAttr(),ClueEnum.OWNER_ID.getAttr(),ClueEnum.PUBLIC_GROUP.getAttr(),ClueEnum.BACK_NUM.getAttr());
        }

        List<FieldAttrEntity> explainList = JsonHelperUtil.parseArray(explains, FieldAttrEntity.class);
        List<JSONObject> selectInfo = new ArrayList<>();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer enable = fieldAttrEntity.getIsOpen();
            String attr = fieldAttrEntity.getAttr();
            if (enable == null || BasicConstant.NO_USE.equals(enable)) {
                continue;
            }
            if (!ShowTypeEnum.listShow(fieldAttrEntity.getShowType())) {
                continue;
            }
            if (removeAttrs.contains(attr)) {
                continue;
            }
            //产品说标准模式的 "公海分组" 负责人也变成前负责人,高级模式 "自动转移"这里负责人变前负责人
            boolean preOwnedFlag = ((customerStandardMode || clueStandardMode) && Objects.equals(getConditionDTO.getIsPublicTransfer(),BasicConstant.TWO))
                    || Objects.equals(getConditionDTO.getIsPublicTransfer(),BasicConstant.ONE);
            if (preOwnedFlag && Objects.equals(attr,ClueEnum.OWNER_ID.getAttr())){
                fieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                fieldAttrEntity.setLabel(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
            }
            //客户公海池分组这边过滤掉重要程度
            boolean isCustomerImportant = Objects.equals(getConditionDTO.getIsPublicTransfer(),BasicConstant.TWO)
                    && Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.CUSTOMER_MANAGEMENT) && CustomerManagementEnum.IMPORTANT_DEGREE.getAttr().equals(attr);
            if(isCustomerImportant){
                continue;
            }
            //客户过滤掉评分字段
            if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.CUSTOMER_MANAGEMENT) && CustomerManagementEnum.SCORE.getAttr().equals(attr)){
                continue;
            }
            //线索过滤掉评分字段
            if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.CLUE) && ClueEnum.SCORE.getAttr().equals(attr)){
                continue;
            }
            String alias = fieldAttrEntity.getAttr();
            Integer isRedundant = fieldAttrEntity.getIsRedundant();
            Integer fieldType = fieldAttrEntity.getFieldType();
            DefaultAttrPoJo defaultAttr = fieldAttrEntity.getDefaultAttr();
            Object initValue = (defaultAttr != null && defaultAttr.getDefaultValue() != null) ? defaultAttr.getDefaultValue() : "";
            List<KeyValuePojo> valueArr = new ArrayList<>();

            if (isRedundant == 0 && FieldTypeEnum.COMBO.getType().equals(fieldType)) {
                valueArr = getValueArr(corpid, formId, alias, getConditionDTO.getBusinessType());
            }
            if (valueArr.isEmpty() && fieldAttrEntity.getItems() != null) {
                valueArr = format2KeyValuePojo(fieldAttrEntity.getItems());
            }
            selectInfo = getByType(selectInfo, fieldAttrEntity.getAttrName(), alias, fieldType, valueArr, fieldAttrEntity.getDateType(), isRedundant);
        }
        getConditionVO.setList(selectInfo);

        return getConditionVO;
    }

    @Override
    public SyncConditionPojo getConditionByAttr(String attr, Long formId, String corpid) throws XbbException {
        SyncConditionPojo syncConditionPojo = new SyncConditionPojo();
        PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (explainEntity == null) {
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218011);
        }
        String explains = explainEntity.getExplains();
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains);
        FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
        if (Objects.nonNull(fieldAttrEntity)) {
            List<JSONObject> selectInfo = new ArrayList<>();
            String alias = fieldAttrEntity.getAttr();
            Integer isRedundant = fieldAttrEntity.getIsRedundant();
            Integer fieldType = fieldAttrEntity.getFieldType();
            DefaultAttrPoJo defaultAttr = fieldAttrEntity.getDefaultAttr();
            Object initValue = (defaultAttr != null && defaultAttr.getDefaultValue() != null) ? defaultAttr.getDefaultValue() : "";
            List<KeyValuePojo> valueArr = new ArrayList<>();
            if (isRedundant == 0 && FieldTypeEnum.COMBO.getType().equals(fieldType)) {
                valueArr = getValueArr(corpid, formId, alias, explainEntity.getBusinessType());
            }
            if (valueArr.isEmpty() && fieldAttrEntity.getItems() != null) {
                valueArr = format2KeyValuePojo(fieldAttrEntity.getItems());
            }
            selectInfo =  getByType(selectInfo, fieldAttrEntity.getAttrName(), alias, fieldType, valueArr, fieldAttrEntity.getDateType(), isRedundant);
            syncConditionPojo.setFieldAttrEntity(fieldAttrEntity);
            syncConditionPojo.setSelectInfo(selectInfo);
        }
        return syncConditionPojo;
    }


    @Override
    public List<PublicGroupEntity> getListByUser(UserEntity user, Long formId) {
        List<PublicGroupEntity> resultList = new ArrayList<>();
        if (user == null) {
            return resultList;
        }

//        List<PublicGroupEntity> list = publicGroupModel.enableListByFormId(user.getCorpid(), formId);
//
//        // 角色数据
//        List<Integer> roleIds = user.roleIdsToList();
//        // 部门列表
//        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//        param.put("corpid", user.getCorpid());
//        param.put("del", DelEnum.NORMAL.getDel());
//        List<DepartmentEntity> allDepartmentList = departmentModel.findEntitys(param);
//        // 获得用户所属部门id列表
//        List<Long> belongDepList = userModel.getUserBelongDeptIdList(user, false);
//
//
//        for (PublicGroupEntity entity : list) {
//            JSONArray scopeRule = entity.getScopeRule();
//            List<OptionalRangeEntity> scopeRuleData;
//            try {
//                scopeRuleData = scopeRule.toJavaList(OptionalRangeEntity.class);
//            } catch (JSONException e) {
//                scopeRuleData = new ArrayList<>();
//            }
//            // 未设置查看权限
//            if (scopeRuleData.size() <= 0) {
//                resultList.add(entity);
//                continue;
//            }
//
//            List<Long> depIdArray = new ArrayList<>();
//            List<Integer> roleIdArray = new ArrayList<>();
//            List<String> userIdArray = new ArrayList<>();
//
//            for (OptionalRangeEntity rangeEntity : scopeRuleData) {
//                String property = rangeEntity.getProperty();
//                String id = rangeEntity.getId();
//
//                if (OptionalRangeEnum.DEPT.getValue().equals(property)) {
//                    depIdArray.add(Long.parseLong(id));
//                } else if (OptionalRangeEnum.ROLE.getValue().equals(property)) {
//                    roleIdArray.add(Integer.parseInt(id));
//                } else if (OptionalRangeEnum.USER.getValue().equals(property)) {
//                    userIdArray.add(id);
//                }
//            }
//
//            // 未设置查看权限
//            if (depIdArray.isEmpty() && roleIdArray.isEmpty() && userIdArray.isEmpty()) {
//                resultList.add(entity);
//                continue;
//            }
//
//            // 角色是否有交集
//            roleIdArray.retainAll(roleIds);
//            if (!roleIdArray.isEmpty()) {
//                resultList.add(entity);
//                continue;
//            }
//
//            // 全公司
//            if (depIdArray.contains(1L)) {
//                resultList.add(entity);
//                continue;
//            }
//
//            // 获取有权限查看模板的部门以及子部门
//            Set<Long> depIncludeSubSet = new LinkedHashSet<>();
//            for (Long depId : depIdArray) {
//                Set<Long> subDepIdList = userService.getSubDepIdList(depId, allDepartmentList);
//                depIncludeSubSet.addAll(subDepIdList);
//            }
//            depIncludeSubSet.retainAll(belongDepList);
//            if (!depIncludeSubSet.isEmpty()) {
//                resultList.add(entity);
//                continue;
//            }
//
//            // 自定义人员匹配
//            if (userIdArray.contains(user.getUserId())) {
//                resultList.add(entity);
//            }
//
//        }

        return getListByUser(user, Collections.singletonList(formId));
    }

    @Override
    public List<PublicGroupEntity> getListByUser(UserEntity user, List<Long> formIdList) {
        if (user == null) {
            return new ArrayList<>();
        }
        List<PublicGroupEntity> list = publicGroupModel.enableListByFormIdList(user.getCorpid(), formIdList);
        if (list.isEmpty()) {
            return new ArrayList<>();
        }
        return filterGroupByUser(list, user);

    }

    @Override
    public List<PublicGroupEntity> filterGroupByUser(List<PublicGroupEntity> list, UserEntity user) {
        return listGroupService.filterGroupByUser(list, user);
    }

    /**
     * 通过登录人匹配高级分组的查看权限和管理员权限字段取分组并集
     * @author lijiangren
     * @date 2022-06-02 10 23
     */
    @Override
    public List<PublicGroupSeniorEntity> filterGroupSeniorByUser(List<PublicGroupSeniorEntity> list, UserEntity user) {
        return publicGroupSeniorModel.filterGroupSeniorByUser(list, user);
    }

    @Override
    public boolean hasAuthToThisForm(UserEntity userEntity, Long formId) {
        boolean hasAuth = false;
        if (userModel.isBoss(userEntity)) {
            // 最高权限直接返回true
            return true;
        }
        String corpid = userEntity.getCorpid();

        Map<String, Object> param = new HashMap<>(16);
        param.put("corpid", corpid);
        param.put("enable", BasicConstant.IS_USE);
        param.put("del", DelEnum.NORMAL.getDel());
        List<PublicGroupEntity> allGroupList = publicGroupModel.findEntitys(param);
        // 该公司没有分组，返回true
        if (allGroupList.size() <= 0) {
            return true;
        }

        // 客户表单关联的公海分组id
        List<PublicGroupEntity> groupList = new ArrayList<>();
        allGroupList.forEach(item -> {
            if (item.getFormId().equals(formId)) {
                groupList.add(item);
            }
        });

        for (PublicGroupEntity publicGroup : groupList) {
            hasAuth = getIsVisible(userEntity, publicGroup);
            if (hasAuth) {
                // 如果有一个可见的那就可见
                break;
            }
        }

        return hasAuth;
    }

    /**
     * 获取分组对用户是否可见
     *
     * @param user        用户实体
     * @param publicGroup 分组实体
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-12 09:16
     * @version v1.0
     * @since v1.0
     */
    private boolean getIsVisible(UserEntity user, PublicGroupEntity publicGroup) {
        Integer scopeEnable = publicGroup.getScopeEnable();
        if (scopeEnable == null || BasicConstant.NO_USE.equals(scopeEnable)) {
            return true;
        }

        JSONArray scopeRule = publicGroup.getScopeRule();
        List<OptionalRangeEntity> scopeRuleData;
        try {
            scopeRuleData = scopeRule.toJavaList(OptionalRangeEntity.class);
        } catch (JSONException e) {
            scopeRuleData = new ArrayList<>();
        }

        if (scopeRuleData.size() <= 0) {
            return true;
        }

        Set<Long> depIdArray = new HashSet<>();
        Set<Long> roleIdArray = new HashSet<>();
        Set<String> userIdArray = new HashSet<>();

        for (OptionalRangeEntity pojo : scopeRuleData) {
            String property = pojo.getProperty();
            String id = pojo.getId();

            // 部门或角色id
            Long longId;
            try {
                longId = Long.parseLong(id);
            } catch (NumberFormatException e) {
                longId = null;
            }

            if (OptionalRangeEnum.DEPT.getValue().equals(property)) {
                depIdArray.add(longId);
            } else if (OptionalRangeEnum.ROLE.getValue().equals(property)) {
                roleIdArray.add(longId);
            } else if (OptionalRangeEnum.USER.getValue().equals(property)) {
                userIdArray.add(id);
            }
        }

        if (depIdArray.isEmpty() || roleIdArray.isEmpty() || userIdArray.isEmpty()) {
            return true;
        }


        Map<String, Object> param = new HashMap<>(8);
        param.put("corpid", user.getCorpid());
        param.put("del", DelEnum.NORMAL.getDel());
        List<DepartmentEntity> allDepartmentList = departmentModel.findEntitys(param);

        boolean matchRole = false;
        boolean matchDep = false;
        boolean matchUser;

        // 角色匹配
        List<Integer> roleIds = user.roleIdsToList();
        for (long roleId : roleIds) {
            if (roleIdArray.contains(roleId)) {
                matchRole = true;
                break;
            }
        }

        // 如果部门规则包含全公司，则直接匹配
        if (depIdArray.contains(1L)) {
            matchDep = true;
        }

        // 获取有权限查看模板的部门以及子部门
        Set<Long> depIncludeSubSet = new LinkedHashSet<>();
        for (Long depId : depIdArray) {
            Set<Long> subDepIdList = userService.getSubDepIdList(depId, allDepartmentList);
            depIncludeSubSet.addAll(subDepIdList);
        }
        List<Long> belongDepList = userModel.getUserBelongDeptIdList(user, false);
        belongDepList.retainAll(depIncludeSubSet);

        if (!belongDepList.isEmpty()) {
            matchDep = true;
        }

        // 自定义人员匹配
        matchUser = userIdArray.contains(user.getUserId());

        return matchRole || matchDep || matchUser;
    }


    /**
     * 获取模板下的公海分组
     *
     * @param formId 模板id
     * @param list   所有公海客户分组
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-04 15:55
     * @version
     * @since
     */
    private List<PublicGroupListPojo> getSubPublicGroup(long formId, List<PublicGroupListPojo> list) {
        List<PublicGroupListPojo> pojoList = new ArrayList<>();
        for (PublicGroupListPojo pojo : list) {
            if (pojo.getFormId() == formId) {
                PublicGroupListPojo newPojo = new PublicGroupListPojo();
                BeanUtil.copyProperties(pojo, newPojo);
                pojoList.add(newPojo);
            }
        }

        return pojoList;
    }

    /**
     * 获取字段筛选项
     *
     * @param corpid 公司id
     * @param formId 客户表单id
     * @param alias  字段别名
     * @param businessType  业务类型
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-06 14:18
     * @version v1.0
     * @since v1.0
     */
    private List<KeyValuePojo> getValueArr(String corpid, Long formId, String alias, Integer businessType) throws XbbException {
        List<KeyValuePojo> jsonArray = new ArrayList<>();
        List<ItemPoJo> valueArr = new ArrayList<>();
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            if (CustomerManagementEnum.GENRE.getAttr().equals(alias)) {
                valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_GENRE, corpid, formId);
            } else if (CustomerManagementEnum.TYPE.getAttr().equals(alias)) {
                valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_STATUS, corpid, formId);
            } else if (CustomerManagementEnum.IS_INDIVIDUAL.getAttr().equals(alias)) {
                valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_IS_INDIVIDUAL, corpid, formId);
            } else if (CustomerManagementEnum.INDUSTRY.getAttr().equals(alias)) {
                valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_INDUSTRY, corpid, formId);
            } else if (CustomerManagementEnum.SOURCE.getAttr().equals(alias)) {
                valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_SOURCE, corpid, formId);
            } else if (CustomerManagementEnum.COUNTRY.getAttr().equals(alias)) {
                valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_COUNTRY, corpid, formId);
            } else if (CustomerManagementEnum.SCALE.getAttr().equals(alias)) {
                // 客户分级
                valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_SCALE, corpid, formId);
            }
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            if (ClueEnum.CLUE_STAGE.getAttr().equals(alias)) {
                valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CLUE_STAGE, corpid, formId);
            }
        }

        if (valueArr != null && valueArr.size() > 0) {
            for (ItemPoJo poJo : valueArr) {
                jsonArray.add(new KeyValuePojo(poJo.getText(), poJo.getValue()));
            }
        }

        return jsonArray;
    }


    /**
     * 格式化筛选的数据
     *
     * @param selectInfo  筛选的数据
     * @param name        名称
     * @param alias       别名
     * @param fieldType   类型
     * @param valueArr    值数组
     * @param dateType   初始值
     * @param isRedundant 是否扩展字段
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-06 14:10
     * @version v1.0
     * @since v1.0
     */
    private List<JSONObject> getByType(List<JSONObject> selectInfo, String name, String alias, Integer fieldType,
                                       List<KeyValuePojo> valueArr, String dateType, Integer isRedundant) {

        JSONObject redundantJson = new JSONObject();
        JSONArray redundantSymbol = new JSONArray();
        JSONArray provinceSymbol = new JSONArray();

        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        if (fieldTypeEnum == null) {
            return selectInfo;
        }

        // 是否放入返回结果
        boolean isPut = false;
        switch (fieldTypeEnum) {
            // 单行、多行
            case TEXT:
            case TEXTAREA:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.LIKE);
                symbolRelation(redundantSymbol, ConditionEnum.NOLIKE);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                isPut = true;
                break;
            // 数字输入
            case NUM:
            case DATETIME:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.GREATERTHAN);
                symbolRelation(redundantSymbol, ConditionEnum.LESSTHAN);
                symbolRelation(redundantSymbol, ConditionEnum.GREATEREQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.LESSEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.RANGE);
                isPut = true;
                break;
            // 下拉、复选框组
            case COMBO:
            case CHECKBOX_GROUP:
            case STAGE_THRUSTER:
                symbolRelation(redundantSymbol, ConditionEnum.LIKE);
                symbolRelation(redundantSymbol, ConditionEnum.NOLIKE);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 单选按钮、流水号
            case RADIO_GROUP:
            case SERIALNO:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.LIKE);
                symbolRelation(redundantSymbol, ConditionEnum.NOLIKE);
                symbolRelation(redundantSymbol, ConditionEnum.IN);
                symbolRelation(redundantSymbol, ConditionEnum.NOIN);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 下拉复选框、成员多选、部门多选
            case COMBO_CHECK:
            case USER_GROUP:
            case DEPT_GROUP:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.INCLUDE);
                symbolRelation(redundantSymbol, ConditionEnum.ALLINCLUDE);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 成员单选、创建人、所属部门、部门单选
            case USER:
            case CREATORID:
            case DEPARTMENTID:
            case DEPT:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.IN);
                symbolRelation(redundantSymbol, ConditionEnum.NOIN);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 添加时间、更新时间
            case ADDTIME:
            case UPDATETIME:
                symbolRelation(redundantSymbol, ConditionEnum.GREATEREQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.LESSEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.RANGE);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 负责人
            case OWNERID:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.IN);
                symbolRelation(redundantSymbol, ConditionEnum.ALLINCLUDE);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            case LABEL:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.INCLUDE);
                symbolRelation(redundantSymbol, ConditionEnum.ALLINCLUDE);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            case PUBLIC_GROUP:
            case STAR:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            default:
                // 地址，省市区
                if (CustomerManagementEnum.ADDRESS.getAttr().equals(alias)) {
                    symbolRelation(provinceSymbol, ConditionEnum.EQUAL);
                    symbolRelation(provinceSymbol, ConditionEnum.NOEQUAL);
                    symbolRelation(provinceSymbol, ConditionEnum.LIKE);
                    symbolRelation(provinceSymbol, ConditionEnum.NOLIKE);
                    symbolRelation(provinceSymbol, ConditionEnum.EMPTY);
                    symbolRelation(provinceSymbol, ConditionEnum.NOEMPTY);
                    symbolRelation(provinceSymbol, ConditionEnum.IN);
                    symbolRelation(provinceSymbol, ConditionEnum.NOIN);
                    redundantJson.put("name", I18nMessageUtil.getMessage(CommonConstant.PROVINCE));
                    redundantJson.put("alias", "province");
                    redundantJson.put("symbolArray", provinceSymbol);
                    redundantJson.put("type", FieldTypeEnum.PUBLIC_GROUP_PROVINCE.getType());
                    redundantJson.put("isRedundant", isRedundant);
                    redundantJson.put("symbol", "");
                    selectInfo.add(redundantJson);
                    symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                    symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                    symbolRelation(redundantSymbol, ConditionEnum.LIKE);
                    symbolRelation(redundantSymbol, ConditionEnum.NOLIKE);
                    symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                    symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                    JSONObject redundantJsonCity = new JSONObject();
                    redundantJsonCity.put("name", I18nMessageUtil.getMessage(CommonConstant.CITY));
                    redundantJsonCity.put("alias", "city");
                    redundantJsonCity.put("symbolArray", redundantSymbol);
                    redundantJsonCity.put("type", FieldTypeEnum.TEXT.getType());
                    redundantJsonCity.put("isRedundant", isRedundant);
                    redundantJsonCity.put("symbol", "");
                    selectInfo.add(redundantJsonCity);
                    JSONObject redundantJsonDistrict = new JSONObject();
                    redundantJsonDistrict.put("name", I18nMessageUtil.getMessage(CommonConstant.AREA));
                    redundantJsonDistrict.put("alias", "district");
                    redundantJsonDistrict.put("symbolArray", redundantSymbol);
                    redundantJsonDistrict.put("type", FieldTypeEnum.TEXT.getType());
                    redundantJsonDistrict.put("isRedundant", isRedundant);
                    redundantJsonDistrict.put("symbol", "");
                    selectInfo.add(redundantJsonDistrict);
                    JSONObject redundantJsonAddress = new JSONObject();
                    redundantJsonAddress.put("name", CustomerExpressEnum.ADDRESS.getName());
                    redundantJsonAddress.put("alias", "address");
                    redundantJsonAddress.put("symbolArray", redundantSymbol);
                    redundantJsonAddress.put("type", FieldTypeEnum.TEXT.getType());
                    redundantJsonAddress.put("isRedundant", isRedundant);
                    redundantJsonAddress.put("symbol", "");
                    selectInfo.add(redundantJsonAddress);
                }
                break;
        }

        if (isPut) {
            redundantJson.put("name", name);
            redundantJson.put("alias", alias);
            redundantJson.put("isRedundant", isRedundant);
            redundantJson.put("symbolArray", redundantSymbol);
            redundantJson.put("symbol", "");
            redundantJson.put("type", fieldType);
            // redundantJson.put("dateType", dateType);
            selectInfo.add(redundantJson);
        }

        return selectInfo;
    }

    /**
     * 获取字段筛选条件
     *
     * @param redundantSymbol 字段条件数据
     * @param symbolEnum      条件枚举
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-06 13:52
     * @version v1.0
     * @since v1.0
     */
    private void symbolRelation(JSONArray redundantSymbol, ConditionEnum symbolEnum) {
        String symbol = symbolEnum.getSymbol();
        String name = symbolEnum.getMemo();
        Map<String, Object> param = new HashMap<>(8);
        param.put("key", symbol);
        param.put("value", name);
        redundantSymbol.add(param);
    }

    /**
     * itemPojo转化为KeyValuePojo
     * TODO 后面还要改造
     *
     * @param valueArr itemPojo列表
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-02 12:41
     * @version v1.0
     * @since v1.0
     */
    private List<KeyValuePojo> format2KeyValuePojo(List<ItemPoJo> valueArr) {
        List<KeyValuePojo> resultList = new ArrayList<>();
        if (valueArr != null && valueArr.size() > 0) {
            for (ItemPoJo poJo : valueArr) {
                resultList.add(new KeyValuePojo(poJo.getText(), poJo.getValue()));
            }
        }
        return resultList;
    }


    /**
     * 根据表单ID公海分组
     * @author lijiangren
     * @date 2022-05-24 19:40
     */
    @Override
    public List<PublicGroupEntity> getListFormIdList(List<Long> formIdList, String corpid) {
        if (CollectionsUtil.isNotEmpty(formIdList)) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("enable", BasicConstant.ONE);
            param.put("formIdIn", formIdList);
            param.put("orderByStr", "sort desc");
            return publicGroupModel.findEntitys(param);
        }
        return null;
    }


    @Override
    public PublicGroupItemListVO groupTabList(PublicGroupSetListDTO setListDTO) throws XbbException {
        Integer businessType = setListDTO.getBusinessType();
        String corpid = setListDTO.getCorpid();
        //判断是否有切换公海模式按钮
        Set<String> permSet = setListDTO.getLoginUser().getPermSet();
        PublicGroupItemListVO setListVO = new PublicGroupItemListVO();
        //是否有公海池切换按钮
        if (permSet.contains(ProPermissionAliasEnum.SWITCH_PUBLIC_MODE.getAlias())) {
            setListVO.setChangePublicPoolPerm(true);
        }
        List<PublicGroupItemListPojo> groupSetItem = new ArrayList<>();
        Boolean ultimateWithFeeType = packageHelp.isUltimateWithFeeType(setListDTO.getCorpid());
        //该公司是否开启客户公海高级模式
        boolean isCustomerSeniorMode = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
        //该公司是否开启线索公海高级模式
        boolean isClueSeniorMode = commonHelp.isCluePublicPoolSeniorModel(corpid);
        //分组设置
        PublicGroupItemListPojo groupPojo = new PublicGroupItemListPojo();
        groupPojo.setAlias("publicGroupRuleSet");
        groupPojo.setBusinessType(businessType);
        groupPojo.setName(I18nMessageUtil.getMessage(StringConstant.PUBLIC_GROUP_RULE_SET));
        groupPojo.setTabType(BasicConstant.ONE);
        groupSetItem.add(groupPojo);
        //自动退回
        PublicGroupItemListPojo backPojo = new PublicGroupItemListPojo();
        backPojo.setAlias("publicBackRuleSet");
        backPojo.setBusinessType(businessType);
        backPojo.setName(I18nMessageUtil.getMessage(StringConstant.PUBLIC_BACK_RULE_SET));
        backPojo.setTabType(BasicConstant.TWO);
        groupSetItem.add(backPojo);

        //自动转移,客户高级模式和线索高级模式分开处理
        boolean transferFlag = (Objects.equals(businessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && isCustomerSeniorMode)
                || (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode()) && isClueSeniorMode);
        if (transferFlag){
            PublicGroupItemListPojo transferPojo = new PublicGroupItemListPojo();
            transferPojo.setAlias("publicTransferRuleSet");
            transferPojo.setBusinessType(businessType);
            transferPojo.setName(I18nMessageUtil.getMessage(StringConstant.PUBLIC_TRANSFER_RULE_SET));
            transferPojo.setTabType(BasicConstant.THREE);
            groupSetItem.add(transferPojo);
        }

        //自动分配
        // 自动分配规则，当套餐不为标准版、市场管理应用开启、销售线索表单开启时才展示
        Boolean standardWithFeeType = packageHelp.isStandardWithFeeType(corpid);
        boolean enableWithApp = marketManagementBusinessHelp.isEnableWithApp(corpid);
        PaasMenuEntity byAlias = paasMenuModel.getByAlias(XbbRefTypeEnum.CLUE.getAlias(), corpid);
        boolean distributionFlag = !standardWithFeeType && enableWithApp && (Objects.nonNull(byAlias) && Objects.equals(byAlias.getEnable(), BasicConstant.ONE));
        if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()) && distributionFlag){
            PublicGroupItemListPojo distributionPojo = new PublicGroupItemListPojo();
            distributionPojo.setAlias("publicDistributionRuleSet");
            distributionPojo.setBusinessType(businessType);
            distributionPojo.setName(I18nMessageUtil.getMessage(StringConstant.PUBLIC_DISTRIBUTION_RULE_SET));
            distributionPojo.setTabType(BasicConstant.FOUR);
            groupSetItem.add(distributionPojo);
        }
        //其他设置
        PublicGroupItemListPojo otherPojo = new PublicGroupItemListPojo();
        otherPojo.setAlias("publicOtherRuleSet");
        otherPojo.setBusinessType(businessType);
        otherPojo.setName(I18nMessageUtil.getMessage(StringConstant.PUBLIC_OTHER_RULE_SET));
        otherPojo.setTabType(BasicConstant.FIVE);
        groupSetItem.add(otherPojo);
        setListVO.setGroupSetItem(groupSetItem);
        return setListVO;
    }


}
